#!/bin/bash

# =============================================================================
# 监控配置脚本
# =============================================================================

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
log_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

log_info "开始监控配置..."

# 创建监控脚本目录
mkdir -p /home/$USER/monitoring

# 创建系统监控脚本
cat > /home/$USER/monitoring/system_monitor.sh << 'EOF'
#!/bin/bash

# 系统监控脚本
LOG_FILE="/var/log/memebot/system_monitor.log"

# 获取系统信息
CPU_USAGE=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)
MEM_USAGE=$(free | awk 'NR==2{printf "%.1f", $3*100/$2}')
DISK_USAGE=$(df -h / | awk 'NR==2{print $5}' | sed 's/%//')
LOAD_AVG=$(uptime | awk -F'load average:' '{print $2}')

# 记录到日志
echo "$(date): CPU=${CPU_USAGE}%, MEM=${MEM_USAGE}%, DISK=${DISK_USAGE}%, LOAD=${LOAD_AVG}" >> $LOG_FILE

# 检查阈值并报警
if (( $(echo "$CPU_USAGE > 80" | bc -l) )); then
    echo "$(date): 警告 - CPU使用率过高: ${CPU_USAGE}%" >> $LOG_FILE
fi

if (( $(echo "$MEM_USAGE > 85" | bc -l) )); then
    echo "$(date): 警告 - 内存使用率过高: ${MEM_USAGE}%" >> $LOG_FILE
fi

if [ "$DISK_USAGE" -gt 85 ]; then
    echo "$(date): 警告 - 磁盘使用率过高: ${DISK_USAGE}%" >> $LOG_FILE
fi
EOF

chmod +x /home/$USER/monitoring/system_monitor.sh

# 创建应用监控脚本
cat > /home/$USER/monitoring/app_monitor.sh << 'EOF'
#!/bin/bash

# 应用监控脚本
LOG_FILE="/var/log/memebot/app_monitor.log"

# 检查PM2状态
if ! pm2 describe memebot-trading > /dev/null 2>&1; then
    echo "$(date): 错误 - 应用未运行" >> $LOG_FILE
    exit 1
fi

# 获取应用信息
APP_STATUS=$(pm2 jlist | jq -r '.[] | select(.name=="memebot-trading") | .pm2_env.status')
APP_CPU=$(pm2 jlist | jq -r '.[] | select(.name=="memebot-trading") | .monit.cpu')
APP_MEM=$(pm2 jlist | jq -r '.[] | select(.name=="memebot-trading") | .monit.memory')
APP_RESTARTS=$(pm2 jlist | jq -r '.[] | select(.name=="memebot-trading") | .pm2_env.restart_time')

# 记录状态
echo "$(date): 状态=${APP_STATUS}, CPU=${APP_CPU}%, 内存=${APP_MEM}B, 重启次数=${APP_RESTARTS}" >> $LOG_FILE

# 检查应用健康
if [ "$APP_STATUS" != "online" ]; then
    echo "$(date): 错误 - 应用状态异常: $APP_STATUS" >> $LOG_FILE
fi

# 检查HTTP响应
if ! curl -f -s http://localhost:3000 > /dev/null 2>&1; then
    echo "$(date): 错误 - HTTP健康检查失败" >> $LOG_FILE
fi
EOF

chmod +x /home/$USER/monitoring/app_monitor.sh

# 创建综合状态脚本
cat > /home/$USER/status_check.sh << 'EOF'
#!/bin/bash

echo "=== MemeBot 系统状态检查 ==="
echo "时间: $(date)"
echo

echo "=== 系统资源 ==="
echo "CPU使用率: $(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)%"
echo "内存使用率: $(free | awk 'NR==2{printf "%.1f%%", $3*100/$2}')"
echo "磁盘使用率: $(df -h / | awk 'NR==2{print $5}')"
echo "系统负载: $(uptime | awk -F'load average:' '{print $2}')"
echo

echo "=== 应用状态 ==="
pm2 status
echo

echo "=== 服务状态 ==="
echo "Nginx: $(systemctl is-active nginx)"
echo "PostgreSQL: $(systemctl is-active postgresql)"
echo

echo "=== 网络连接 ==="
echo "端口3000: $(netstat -tulpn | grep :3000 | wc -l) 个连接"
echo

echo "=== 最近日志 ==="
echo "应用日志:"
pm2 logs memebot-trading --lines 3 --nostream 2>/dev/null || echo "无法获取日志"
EOF

chmod +x /home/$USER/status_check.sh

# 添加监控定时任务
(crontab -l 2>/dev/null; echo "# MemeBot 监控任务") | crontab -
(crontab -l 2>/dev/null; echo "*/10 * * * * /home/$USER/monitoring/system_monitor.sh") | crontab -
(crontab -l 2>/dev/null; echo "*/5 * * * * /home/$USER/monitoring/app_monitor.sh") | crontab -

log_success "监控配置完成！"
log_info "监控脚本位置:"
echo "  /home/$USER/monitoring/system_monitor.sh - 系统监控"
echo "  /home/$USER/monitoring/app_monitor.sh    - 应用监控"
echo "  /home/$USER/status_check.sh             - 状态检查"
echo
log_info "监控日志位置:"
echo "  /var/log/memebot/system_monitor.log - 系统监控日志"
echo "  /var/log/memebot/app_monitor.log    - 应用监控日志"
